﻿using HarmonyLib;
using RimWorld;
using RimWorld.Planet;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using Verse;
using Verse.AI;
using UnityEngine;

namespace Miao.Stand
{
    [HarmonyPatch(typeof(Dialog_FormCaravan), "TryReformCaravan")]
    public class Dialog_FormCaravan_TryReformCaravan
    {
        static void Prefix(Dialog_FormCaravan __instance)
        {

        }
    }
    /// <summary>
    /// 自动选择最好旅行用品
    /// </summary>
    [HarmonyPatch(typeof(Dialog_FormCaravan), "SelectApproximateBestTravelSupplies")]
     static class Dialog_FormCaravan_SelectApproximateBestTravelSupplies
    {
        static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
        {
            var instructionsList = new List<CodeInstruction>(instructions);//instructionsList是操作IL码
            for (var i = 0; i < instructionsList.Count; i++)
            {
                CodeInstruction instruction = instructionsList[i];
                //operand操作数 如果操作的方法==WildManUtility中的AnimalOrWildMan方法，将方法替换为AnimalOrWildManOrHacked这个方法。
                if (instruction.operand as MethodInfo == AccessTools.Method(typeof(WildManUtility), "AnimalOrWildMan"))
                {
                    yield return new CodeInstruction(OpCodes.Call, typeof(Dialog_FormCaravan_SelectApproximateBestTravelSupplies).GetMethod("AnimalOrWildManOrStand"));
                }
                //else if (instruction.operand as MethodInfo == AccessTools.Method(typeof(Dialog_FormCaravan_SelectApproximateBestTravelSupplies), "AnimalOrWildManOrHacked"))//给HackMod打补丁
                //{
                //    yield return new CodeInstruction(OpCodes.Call, typeof(Dialog_FormCaravan_SelectApproximateBestTravelSupplies).GetMethod("HackModPatchOrStand"));
                //}
                else
                {
                    yield return instruction;
                }
            }
        }

        public static bool AnimalOrWildManOrStand(Pawn pawn)
        {
            return WildManUtility.AnimalOrWildMan(pawn)||pawn.IsStand();
        }

        public static bool HackModPatchOrStand(Pawn pawn)
        {
            return Dialog_FormCaravan_SelectApproximateBestTravelSupplies.AnimalOrWildManOrStand(pawn) || pawn.IsStand();
        }
    }
}
